package org.popupcommunication.utils;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.popupcommunication.exceptions.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

public abstract class FileUtil {
	@Autowired
	private static ServletContext srvContext;

	static private Log log = LogFactory.getLog(FileUtil.class);

	final static public String USER_AVATAR = "/user/avatar";	

	public static String getGenFolderPath() {
		return srvContext.getRealPath("/");
	}

	public static String renameFile(String path,String newName,String oldName){
		File oldfile =new File(path+"/"+oldName);
		int i = oldName.lastIndexOf('.');
		String extension ="";
		if (i >= 0) {
		    extension = oldName.substring(i);
		}		
		File newfile =new File(path+"/"+newName+extension);	
		if(oldfile.renameTo(newfile))
			return newName+extension;
		return oldName;
		
	}
	
	public static File uploadFile(MultipartFile multipartFile, String path,
			String fileName) throws FileUploadException, Exception {
		if (multipartFile.getSize() > 1500000) {
			throw new FileUploadException("file is too large 1.5Mo maximum");
		}
		if (path == null) {
			throw new FileUploadException("File path(image) can't be null");
		}

		if (fileName == null) {
			throw new FileUploadException("File name(image) can't be null");
		}
		File folder = FileUtil.ensureFolderExists(path);
		if (log.isDebugEnabled()) {
			log.debug("genFolder : " + folder.getAbsolutePath());
			log.debug("file type is :" + multipartFile.getContentType());
			log.debug("file original name is "
					+ multipartFile.getOriginalFilename());
		}

		if (multipartFile.isEmpty()) {
			if (log.isDebugEnabled()) {
				log.debug("someone try to submit an empty file : "
						+ multipartFile.getOriginalFilename());
			}
			throw new FileUploadException("No file to transfer. File is empty.");

		}

		File file = new File(folder, fileName);

		FileOutputStream fos = null;
		fos = new FileOutputStream(file);
		fos.write(multipartFile.getBytes());
		fos.close();

		log.debug("file succesfull uploaded : " + file.getCanonicalPath());
		return file;
	}

	public static File ensureFolderExists(String completeFolderName) {
		File mainFolder = new File(completeFolderName);
		if (!mainFolder.exists()) {
			mainFolder.mkdirs();
		}
		return mainFolder;
	}
	private static double determineImageScale(int sourceWidth, int sourceHeight, int targetWidth, int targetHeight) {

		double scalex = (double) targetWidth / sourceWidth;
		double scaley = (double) targetHeight / sourceHeight;
		return Math.min(scalex, scaley);
	}
	
	public static BufferedImage resizeImage(BufferedImage originalImage,
			int type, int w, int h) {
		double ratio = determineImageScale(originalImage.getWidth(),originalImage.getHeight(),w,h);
		w = (int) (originalImage.getWidth() * ratio);
		h = (int) (originalImage.getHeight() * ratio);
		Image scaledImage = originalImage.getScaledInstance(w, h, Image.SCALE_SMOOTH);		
		BufferedImage resizedImage = new BufferedImage(w, h,type);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(scaledImage, 0, 0, w, h, null);
		g.dispose();	
		return resizedImage;
	}
}
